﻿using System;
using System.Collections.Generic;
using System.Linq;
using Citi.Import.Util;
using Citi.ResourceConsolidation.Domain.Utils;

namespace Citi.ResourceConsolidation.Domain
{
    public partial class DomicileCountry
    {
        private const string CountryOfDomicileColumn = "Country of Domicile";

        public static readonly List<Definition<DomicileCountry>> Definitions = new List<Definition<DomicileCountry>>
            {
                new Definition<DomicileCountry> { ModelProperty = x => x.Description, Required = true, ColumnName = CountryOfDomicileColumn, CustomConversionMethod = ValidateCountry},
            };

        private static object ValidateCountry(ref DomicileCountry model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                error = String.Format("The field {0} can not be null", CountryOfDomicileColumn);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(new DomicileCountry().SelectAll<DomicileCountry>).FirstOrDefault(x => x.Description == value);

            if (domain != null)
            {
                model = domain;
                return Conversion.Validation.Validated;
            }

            return value;
        }

        public static void Save(List<DomicileCountry> countries)
        {
            countries = countries.Distinct(new DomicileCountryCompare()).Where(x => x != null && !String.IsNullOrEmpty(x.Description) && x.Id == 0).ToList();

            if (!countries.Any()) return;
            countries.First().Save(countries, 100);

            CacheFacade.Clear(typeof(DomicileCountry));
            Context.ClearContext();
        }
    }

    public class DomicileCountryCompare : IEqualityComparer<DomicileCountry>
    {
        public bool Equals(DomicileCountry x, DomicileCountry y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Id == y.Id;
        }

        public int GetHashCode(DomicileCountry item)
        {
            if (ReferenceEquals(item, null)) return 0;

            int hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            int hashId = item.Description == null ? 0 : item.Id.GetHashCode();

            return hashDescription ^ hashId;
        }
    }
}
